package org.jsola.contract.web;

import jodd.util.StringUtil;
import org.apache.commons.io.FilenameUtils;
import org.jsola.contract.constant.ContractConstants;
import org.jsola.contract.dto.ContractAddDTO;
import org.jsola.contract.dto.ContractBatchDTO;
import org.jsola.contract.dto.ContractUpdateDTO;
import org.jsola.contract.dto.PdfToContractAddDTO;
import org.jsola.contract.entity.ContractDO;
import org.jsola.contract.query.ContractQuery;
import org.jsola.contract.service.IContractService;
import org.jsola.contract.vo.ContractListVO;
import org.jsola.contract.vo.ContractVO;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.file.common.FileUtil;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import javax.validation.Valid;


/**
 * 合同
 *
 * @author JanusMix
 */
@RestController("contractContractController")
@RequestMapping(ContractConstants.API_PATH + "/v1/contracts")
public class ContractController implements IContractControllerAPI {

    @Autowired
    private IContractService contractService;

    @Override
    @PostMapping
    public Result<ContractVO> save(@Valid @RequestBody ContractAddDTO contractAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增合同权限校验

        return Result.success(
                contractService.save(contractAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody ContractUpdateDTO contractUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改合同权限校验

        int count = contractService.update(contractUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @PostMapping(value = "/batch")
    public Result batch(@Valid @RequestBody ContractBatchDTO contractBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量操作权限校验

        // 批量操作，注意校验，有越权风险
        // 新增
        List<ContractAddDTO> contractAddDTOList = contractBatchDTO.getContractAddDTOList();
        if (!CollectionUtils.isEmpty(contractAddDTOList)) {
            contractService.batchSave(contractAddDTOList, tokenUser);
        }
        // 修改
        List<ContractUpdateDTO> contractUpdateDTOList = contractBatchDTO.getContractUpdateDTOList();
        if (!CollectionUtils.isEmpty(contractUpdateDTOList)) {
            contractUpdateDTOList.parallelStream().forEach(
                    contractUpdateDTO -> {
                        contractService.update(contractUpdateDTO, tokenUser);
                    }
            );
        }
        // 删除
        List<Long> deleteContractIdList = contractBatchDTO.getDeleteContractIdList();
        if (!CollectionUtils.isEmpty(deleteContractIdList)) {
            contractService.deleteByIds(tokenUser, deleteContractIdList.toArray(new Long[0]));
        }
        return Result.success();
    }


    @Override
    @DeleteMapping(value = "/{contractId}")
    public Result<Integer> delete(@PathVariable Long contractId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除合同权限校验

        int count = contractService.deleteByIds(tokenUser, contractId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody Long[] contractIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除合同权限校验

        int count = contractService.deleteByIds(tokenUser, contractIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{contractId}")
    public Result<ContractVO> findById(@PathVariable Long contractId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看合同权限校验

        return Result.success(
                contractService.selectById(contractId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<ContractListVO>> listAll(@Valid ContractQuery contractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看合同权限校验

        return Result.success(
                contractService.select(contractQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<ContractListVO>> page(@Valid ContractQuery contractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                contractService.selectPage(contractQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PutMapping(value = "/updateContractNoById/{contractId}")
    public Result<String> updateContractNoById(@PathVariable Long contractId, @RequestBody ContractUpdateDTO contractUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        ContractDO contractDO = new ContractDO();
        contractDO.setId(contractId);
        contractDO.setPublishDate(contractUpdateDTO.getPublishDate());
        contractDO.setEndDate(contractUpdateDTO.getEndDate());
        if (StringUtil.isNotBlank(contractUpdateDTO.getContractNo())) {
            contractDO.setContractNo(contractUpdateDTO.getContractNo());
        }
        int upCount = contractService.updateByIdSelective(contractDO, tokenUser.getSiteId(), tokenUser.getUserId());
        if (upCount > 0) {
            return Result.success("修改成功");
        } else {
            return Result.fail("修改失败");
        }
    }

    @Override
    @PutMapping(value = "/updateAppShowById/{contractId}/{isShow}")
    public Result<String> updateAppShowById(@PathVariable Long contractId,
                                            @PathVariable Boolean isShow) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        contractService.updateAppShowById(contractId, isShow, tokenUser);
        return Result.success("修改成功");
    }

    @Override
    @PostMapping("/savePdfContract")
    public Result<Integer> saveWordToContract(@Valid @RequestBody PdfToContractAddDTO pdfToContractAddDTO) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(contractService.saveWordToContract(pdfToContractAddDTO, tokenUser));
    }

}

